package cn.edu.pzhu.javaweb.controller;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.edu.pzhu.javaweb.pojo.User;
import cn.edu.pzhu.javaweb.pojo.Userinfo;

/**
 * Servlet implementation class RegistServlet
 */
@WebServlet("/regist")
public class RegistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//编码
		//request.setCharacterEncoding("utf-8");//设置接收参数的编码
		response.setContentType("text/html"); //响应编码
		//接受参数
		String username = request.getParameter("username");//接收用户名
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		String sex = request.getParameter("sex");
		String[] types = request.getParameterValues("type");
		String captcha = request.getParameter("captcha");

		StringBuilder errorMsg = new StringBuilder();

		// 性别验证
		if (sex == null || !(sex.equals("0") || sex.equals("1"))) {
			errorMsg.append("性别数据错误（未获取到0或1）");
		}

		//用户名验证
		if (username == null || username.trim().isEmpty()) {
			errorMsg.append("用户名不能为空");
		} else {
			ServletContext application = request.getServletContext();
			Object object = application.getAttribute(username+"_user");
			if (object != null){
				errorMsg.append("用户名已经被注册");
			}
		}

		//密码验证
		if (password == null || password.trim().isEmpty()) {
			errorMsg.append("密码不能为空");
		} else if (password.length() < 6) {
			errorMsg.append("密码长度不能小于6位");
		}

		// 邮箱验证
		if (email == null || email.trim().isEmpty()) {
			errorMsg.append("邮箱不能为空");
		} else if (!email.matches("\\w+@\\w+\\.\\w+")) {
			errorMsg.append("邮箱格式不正确");
		}

		// 关注类型验证
		if (types == null || types.length == 0) {
			errorMsg.append("没有选择关注类型");
		}

		if (errorMsg.length() > 0) {
			request.setAttribute("error", errorMsg.toString());
			request.getRequestDispatcher("/error.jsp").forward(request, response);
			return;
		}

		//验证和类型转换（防御性编程）
		if(username==null || password==null || username.isEmpty() || password.length()==0) {
			//失败
			response.getWriter().print("<script>alert('用户名和密码不能为空!');location.href='regist.jsp';</script>");
			return;
		}
		if(sex==null || "".equals(sex)) {
			sex="0";
		}
		Integer gender = Integer.valueOf(sex);
		String type = JSON.toJSONString(types);
		if(!"gbcw".equals(captcha)) {
			response.getWriter().print("<script>alert('验证码错误!');location.href='regist.jsp';</script>");
			return;
		}
		//数据封装		
		User user = new User(username, password, 1);
		Userinfo userinfo = new Userinfo(username, email, gender, type);
		//调用模型层方法来写入数据库（暂时写入server容器中）
		ServletContext application = request.getServletContext();
		
		Object object = application.getAttribute(username+"_user");//在存入之前，尝试去取这个用户信息
		if(object!=null) {
			response.getWriter().print("<script>alert('此用户已经存在!');location.href='regist.jsp';</script>");
			return;
		}
		
		application.setAttribute(username+"_user", user);
		application.setAttribute(username+"_userinfo", userinfo);
		response.getWriter().print("<script>alert('注册成功!');location.href='login.jsp';</script>");
		return;	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doGet(request, response);
	}

}
